package com.hethongviet.vending.helper.adapter;

import java.util.List;

import com.hethongviet.vending.R;
import com.hethongviet.vending.model.Box;
import com.hethongviet.vending.model.BoxItem;
import com.hethongviet.vending.model.Product;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class ListItemBoxAdapter extends ArrayAdapter<BoxItem>
{
	private final List<BoxItem> values;
	private final Activity activity;

	/* Make higher performance */
	private static class ViewHolder
	{
		public TextView _textBoxCode;
		public TextView _textProductCode;
		public TextView _textProductName;
		public TextView _textProductAmount;
	}

	public ListItemBoxAdapter(Activity activity, List<BoxItem> values)
	{
		super(activity, R.layout.list_item_box, values);
		this.values = values;
		this.activity = activity;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		View rowView = convertView;
		final ViewHolder viewHolder;

		if (rowView == null)
		{
			LayoutInflater layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			rowView = layoutInflater.inflate(R.layout.list_item_box, parent, false);
			viewHolder = new ViewHolder();
			viewHolder._textBoxCode = (TextView) rowView.findViewById(R.id.text_box_code);
			viewHolder._textProductCode = (TextView) rowView.findViewById(R.id.text_box_product_code);
			viewHolder._textProductAmount = (TextView) rowView.findViewById(R.id.text_box_product_amount);
			viewHolder._textProductName = (TextView) rowView.findViewById(R.id.text_box_product_name);
			rowView.setTag(viewHolder);
		}
		else
		{
			viewHolder = (ViewHolder) rowView.getTag();
		}
		/* Initiate items */
		final Box currentBox = values.get(position).getBox();
		final Product currentProduct = values.get(position).getProduct();

		viewHolder._textBoxCode.setText("" + currentBox.getId());

		if (currentProduct != null)
		{
			viewHolder._textProductAmount.setText(""
					+ currentBox.getProductAmount());

			String name = currentProduct.getName();
			int maxStringLeng = 14;
			if (name != null && name.length() > maxStringLeng) viewHolder._textProductName.setText((name).substring(0, maxStringLeng - 2)
					+ "...");
			else viewHolder._textProductName.setText(name);
			
			viewHolder._textProductCode.setText(currentBox.getProductCode());
		}
		else
		{
			viewHolder._textProductAmount.setText("---");
			viewHolder._textProductName.setText("---");
			viewHolder._textProductCode.setText("---");
		}
		/* Return view */
		return rowView;
	}
}
